//
//  TableCell.m
//  HBTobaccoHD
//
//  Created by M ac on 11-1-7.
//  Copyright 2011 Tiantium. All rights reserved.
//

#import "TableCell3.h"
#import "CommonUtil.h"
#import "HubuAppDelegate.h"
#import "HubuViewController.h"
#import "BookDetailViewController.h"

@implementation TableCell3
@synthesize title, author, column, vote, faceImage, starImage, buyButton, waitingView, fileImageView;

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        // Initialization code.
    }
    return self;
}


- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    
    [super setSelected:selected animated:animated];
    
    // Configure the view for the selected state.
}


- (void)dealloc {    
    [title release];
    [author release];
    [column release];
    [vote release];
    [faceImage release];
    [starImage release];
    [buyButton release];
    [waitingView release];
    [fileImageView release];
    
    [super dealloc];
}


-(void)initExtend:(BookItem *)bookItem {
    localBookItem = bookItem;
    
    title.text = [bookItem bookName];
    author.text = bookItem.bookAuthor;
    if(bookItem.bookTranslator != nil && ![bookItem.bookTranslator isEqualToString:@""]){
        author.text = [NSString stringWithFormat:@"%@ %@ 译", bookItem.bookAuthor, bookItem.bookTranslator];
    }
    column.text = bookItem.bookCategory1;
    starImage.image = [UIImage imageNamed:[NSString stringWithFormat:@"book_star_%@.png", bookItem.bookStar]];
    //vote.text = [NSString stringWithFormat:@"%@ 次下载    %@ 次关注    %@ 份评价", bookItem.bookDownCount, bookItem.bookFocusCount, bookItem.bookCommentCount];
    vote.text = [NSString stringWithFormat:@"%@ 次下载   %@ 次关注", bookItem.bookDownCount, bookItem.bookFocusCount];
    
    NSString *fileType = @"";
    if([localBookItem book4PadResourceType] != nil && ![[localBookItem book4PadResourceType] isEqualToString:@""]) {
        fileType = [localBookItem book4PadResourceType];
    }else{
        fileType = [localBookItem book4PhoneResourceType];
    }
    if([[fileType uppercaseString] isEqualToString:@"TXT"]){
        fileImageView.image = [UIImage imageNamed:@"file_txt.png"];
    }
    /*下载后显示
     NSData* imageData = [[NSData alloc]initWithContentsOfURL:
     [NSURL URLWithString:
     [NSString stringWithFormat:@"http://www.tingl8.com/files/icon/%@", 
     [bookItem bookIcon]]]];
     coverImageView.image = [[UIImage alloc] initWithData:imageData];
     [imageData release];
     */
    /*异步下载后显示
     NSOperationQueue *queue = [NSOperationQueue new];
     [queue setMaxConcurrentOperationCount:1];
     
     
     NSInvocationOperation *operation = [[NSInvocationOperation alloc] 
     initWithTarget:self
     selector:@selector(loadImage:) 
     object:[NSString stringWithFormat:@"http://221.232.130.117:8080/files/i120/%@", [bookItem bookIconSmall]]];
     [waitingView startAnimating];
     [queue addOperation:operation]; 
     [operation release];
     */
    
    //如果图片在本地，则直接显示，否则从服务端下载图片再显示
    if(/*[bookItem bookIconFlag] != nil && ![[bookItem bookIconFlag] isEqualToString:@""] &&*/
       [[NSFileManager defaultManager] fileExistsAtPath:[kDocumentFolder stringByAppendingPathComponent:[bookItem bookIconSmall]]]
       ){
        faceImage.image = [UIImage imageWithContentsOfFile:[kDocumentFolder stringByAppendingPathComponent:[bookItem bookIconSmall]]];
    }else{//下载图片，并保存到本地
        [waitingView startAnimating];
        
        /*
         NSURL *url2=[NSURL URLWithString:
         [NSString stringWithFormat:@"%@%@%@", kServerURL, kFilei120, [bookItem bookIconSmall]]];
         
         NSLog(@"downloadImage:%@", [NSString stringWithFormat:@"%@%@%@", kServerURL, kFilei120, [bookItem bookIconSmall]]);
         
         [url2 dumbDownloadWithDelegate:self Title:@"BookCoverImage" WithToFileName:[kDocumentFolder stringByAppendingPathComponent:[bookItem bookIconSmall]]];
         */
        //在接入网络的情况下，下载图片
        if([CommonUtil isConnected]){
            NSOperationQueue *queue = [NSOperationQueue new];
            [queue setMaxConcurrentOperationCount:1];
            NSInvocationOperation *operation = [[NSInvocationOperation alloc] 
                                                initWithTarget:self
                                                selector:@selector(loadImage:) 
                                                object:[NSString stringWithFormat:@"%@%@%@", kServerURL, kFilei120, [bookItem bookIconSmall]]];
            [waitingView startAnimating];
            [queue addOperation:operation]; 
            [operation release];
        }
        /*
         DumbDownloadManager *downloadManager=[[DumbDownloadManager alloc] init];
         downloadManager.title = @"BookCoverImage";
         downloadManager.fileURL=[NSURL URLWithString:[NSString stringWithFormat:@"%@%@%@", kServerURL, kFilei120, [bookItem bookIconSmall]]];
         downloadManager.fileName=[NSString stringWithFormat:@"%@%@", kDocumentFolder, [bookItem bookIconSmall]];
         downloadManager.delegate = self;
         [downloadManager start];
         */
    }
    
    //NSLog(@"down-buy:%@,%@", [bookItem bookDownFlag], [bookItem bookBuyFlag]);
    //设置下载按钮的文字及事件
    if([[bookItem bookDownFlag] isEqualToString:@"1"]){
        /*
         [buyButton setTitle:@"阅读" forState:UIControlStateNormal];
         [buyButton removeTarget:self action:@selector(buyButtonClick:) forControlEvents:UIControlEventTouchUpInside];
         [buyButton addTarget:self action:@selector(readButtonClick:) forControlEvents:UIControlEventTouchUpInside];
         */
        /*
        [buyButton setTitle:@"已下载" forState:UIControlStateNormal];
        buyButton.enabled = NO;
        [buyButton removeTarget:self action:@selector(buyButtonClick:) forControlEvents:UIControlEventTouchUpInside];
         */
        [buyButton setTitle:@"阅读" forState:UIControlStateNormal];
        [buyButton removeTarget:self action:@selector(buyButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        [buyButton addTarget:self action:@selector(readButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        
    }else if([[bookItem bookBuyFlag] isEqualToString:@"1"]){
        [buyButton setTitle:@"下载" forState:UIControlStateNormal];
    }else{
        if([[bookItem bookPrice] isEqualToString:@"0"]){
            [buyButton setTitle:@"免费" forState:UIControlStateNormal];
        }else{
            /*[buyButton setTitle:[NSString stringWithFormat:@"￥%1.2f", [[bookItem bookPrice] intValue]*6.0] forState:UIControlStateNormal];
             */
            NSLocale* curentLocale = [NSLocale currentLocale];
            //NSLog(@"curentLocale.description=%@", curentLocale.localeIdentifier);
            if([curentLocale.localeIdentifier isEqualToString:@"zh_CN"]){
                [buyButton setTitle:[NSString stringWithFormat:@"￥%1.2f", [[bookItem bookPrice] intValue]*6.0] forState:UIControlStateNormal];
            }else{
                [buyButton setTitle:[NSString stringWithFormat:@"$%1.2f", [[bookItem bookPrice] intValue]*1.0 - 0.01] forState:UIControlStateNormal];
            }
            //priceLabel.text = [NSString stringWithFormat:@"$%1.2f", [[bookItem bookPrice] intValue] - 0.01];
        }
    }
}


-(IBAction)buyButtonClick:(id)sender {
    if(![CommonUtil isConnected]) {
        UIAlertView *alert = [[UIAlertView alloc] 
                              initWithTitle:@"无法连接到服务器" 
                              message:@"请检查设备是否已打开3G网络或者通过Wi-Fi接入互联网。"  
                              delegate:self cancelButtonTitle:@"确定" 
                              otherButtonTitles:nil, nil];
        [alert show];
        [alert release];
        return;
    }
    
    HubuAppDelegate *delegate = [[UIApplication sharedApplication] delegate];
    if(delegate.hubuViewController.isDownloading){
        UIAlertView *alert = [[UIAlertView alloc] 
                              initWithTitle:@"请等待..." 
                              message:@"已经有图书正在下载，请下载完后再下载其他图书。"  
                              delegate:self cancelButtonTitle:@"确定" 
                              otherButtonTitles:nil, nil];
        [alert show];
        [alert release];
        return;
    }
    
    UIButton *b = (UIButton *)sender;
    CGPoint p = [b convertPoint:[b frame].origin toView:delegate.hubuViewController.view];
    delegate.hubuViewController.downloadingButtonTitle = [buyButton titleLabel].text;
    delegate.hubuViewController.downloadButtonTag = b.tag;
    //NSLog(@"b.tag:%d", b.tag);
    [delegate.hubuViewController downloadStart:p bookItem:localBookItem];
    
    if([localBookItem.bookPrice isEqualToString:@"0"]){
        //设置正在下载全局变量
        delegate.hubuViewController.isDownloading = TRUE;
        [buyButton setTitle:@"下载中" forState:UIControlStateNormal];
        [buyButton removeTarget:self action:@selector(buyButtonClick:) forControlEvents:UIControlStateNormal];
        [buyButton setEnabled:NO];
        
        [delegate.hubuViewController downloadStartNow];
    }else{
        [self requestProductData];
    }
    
    
    
//    if([CommonUtil isConnected]) {
//        CommonDownloadWebServices *ws = [[CommonDownloadWebServices alloc] init];
//        [ws setDelegate:self];
//        [ws getWebServicesData:[localBookItem bookId] type:@"d"];
//        [ws release];
//    }
    
    /*下载
     downloadManager=[[DownloadManager alloc] init];
     downloadManager.title= titleLabel.text;
     downloadManager.fileURL=[NSURL URLWithString:[NSString stringWithFormat: @"%@files/this_is_source_folder/pad/%@_4.pdf", kServerURL, [localBookItem bookId]]];
     //downloadManager.fileName=[kDocumentFolder stringByAppendingPathComponent:[localBookItem book4PadResource]];
     NSString *fileName = [[localBookItem book4PadResource] stringByDeletingPathExtension];
     fileName = [NSString stringWithFormat:@"%@.pdf",fileName];
     
     downloadManager.fileName=[kDocumentFolder stringByAppendingPathComponent:fileName];
     downloadManager.delegate = self;
     [downloadManager start];
     */
}


-(IBAction)readButtonClick:(id)sender {
    //NSString *filePath = [CommonUtil unZipData:[localBookItem book4PadResource] extName:[localBookItem book4PadResourceType]];
    NSString *fileName = @"";
    NSString *fileType = @"";
    if([localBookItem book4PhoneResourceType] != nil && ![[localBookItem book4PhoneResourceType] isEqualToString:@""]) {
        fileName = [[localBookItem book4PhoneResource] stringByDeletingPathExtension];
        fileName = [NSString stringWithFormat:@"%@.%@",fileName, [localBookItem book4PhoneResourceType]];
        fileType = [localBookItem book4PhoneResourceType];
    }else{
        fileName = [[localBookItem book4PadResource] stringByDeletingPathExtension];
        fileName = [NSString stringWithFormat:@"%@.%@",fileName, [localBookItem book4PadResourceType]];
        fileType = [localBookItem book4PadResourceType];
    }
    
    if([fileName isEqualToString:@""] || [fileType isEqualToString:@""]){
        return;
    }
    
    if([fileType isEqualToString:@"txt"]){
        /*
         TextViewerController *controller = [[TextViewerController alloc] 
         initWithNibName:@"TextViewerController" bundle:nil];
         controller.bookNameLabel.text = [localBookItem bookName];
         controller.bookNameLabel2.text = [localBookItem bookName];
         controller.bookId = [localBookItem bookId];
         controller.bookFileName = [kDocumentFolder stringByAppendingPathComponent:fileName];
         [controller initExtend];
         [parentObject presentModalViewController:controller animated:YES]; 
         [controller release];*/
        
        TextReaderController *controller = [[[TextReaderController alloc] init] autorelease];
        controller.bookId = [localBookItem bookId];
        controller.bookFileName = [kDocumentFolder stringByAppendingPathComponent:fileName];
        [controller initExtend];
        HubuAppDelegate *delegate = [[UIApplication sharedApplication] delegate];
        [delegate.hubuViewController presentModalViewController:controller animated:YES]; 
    }else{
        
        ReaderDocument *document = [ReaderDocument unarchiveFromFileName:fileName];
        // Create a brand new ReaderDocument object the first time we run
        if (document == nil) {
            document = [[[ReaderDocument alloc] initWithFilePath:
                         [kDocumentFolder stringByAppendingPathComponent:fileName] 
                                                        password:nil] autorelease];
        }
        
        ReaderViewController *readerViewController = [[ReaderViewController alloc] initWithReaderDocument:document];
        readerViewController.title = [localBookItem bookName];
        readerViewController.bookId = [localBookItem bookId];
        readerViewController.delegate = self; // Set the ReaderViewController delegate to self
        readerViewController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
        readerViewController.modalPresentationStyle = UIModalPresentationFullScreen;
        
        HubuAppDelegate *delegate = [[UIApplication sharedApplication] delegate];
        [delegate.hubuViewController presentModalViewController:readerViewController animated:YES];    
        [readerViewController release]; // Release the ReaderViewController
    }
}

- (void) dumbDownloadManagerDataDownloadFinished: (NSString *) fileName {
    DBUtil *db = [[DBUtil alloc] init];
    [db openDB];
    [db updateBook:@"icon" key:[localBookItem bookId] value:@"1"];
    [db closeDB];
    [db release];
    
    if([[NSFileManager defaultManager] fileExistsAtPath:[kDocumentFolder stringByAppendingPathComponent:[localBookItem bookIconSmall]]]
       ){
        faceImage.image = [UIImage imageWithContentsOfFile:[kDocumentFolder stringByAppendingPathComponent:[localBookItem bookIconSmall]]];
    }
    
    [waitingView stopAnimating];
}

- (void) dumbDownloadManagerDataDownloadFailed: (NSString *) reason {
	NSLog(@"dumb download failed:%@", reason);
}


-(void)loadImage:(NSString *)url {
    NSData* imageData = [[NSData alloc]initWithContentsOfURL:
                         [NSURL URLWithString:url]];
    [self writeToFile:imageData];
    faceImage.image = [[UIImage alloc] initWithData:imageData];
    [imageData release];
    [waitingView stopAnimating];
}

-(void)writeToFile:(NSData *)data{
	NSString *filePath= [NSString stringWithFormat:@"%@/%@", kDocumentFolder, [localBookItem bookIconSmall]];
	if([[NSFileManager defaultManager] fileExistsAtPath:filePath] == NO){
		[[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil];
	}
	FILE *file = fopen([filePath UTF8String], [@"ab+" UTF8String]);
	if(file != NULL){
		fseek(file, 0, SEEK_END);
	}
	int readSize = [data length];
	fwrite((const void *)[data bytes], readSize, 1, file);
	fclose(file);
}

-(IBAction)detailButtonClick:(id)sender {
    /*
    BookDetailViewController *controller = [[BookDetailViewController alloc] 
                                            initWithNibName:@"BookDetailViewController" bundle:nil];
    controller.bookId = [localBookItem bookId];
	//controller.resourceItem = [videoList objectAtIndex:((UIButton *)sender).tag];
	controller.modalPresentationStyle = UIModalPresentationFormSheet;
	controller.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
	[parentObject presentModalViewController: controller animated: YES];
	controller.view.superview.frame = CGRectMake(148, 145, 720, 478);
	//controller.view.superview.center = pt;
     */
    BookDetailViewController *controller = [[BookDetailViewController alloc] 
                                            initWithNibName:@"BookDetailViewController" bundle:nil];
    controller.bookId = [localBookItem bookId];
	//controller.resourceItem = [videoList objectAtIndex:((UIButton *)sender).tag];
	controller.modalPresentationStyle = UIModalPresentationFormSheet;
	controller.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    HubuAppDelegate *delegate = [[UIApplication sharedApplication] delegate];
	[delegate.hubuViewController presentModalViewController: controller animated: YES];
	controller.view.superview.frame = CGRectMake(0, 0, 320, 460);
	//controller.view.superview.center = pt;
    
//    if([CommonUtil isConnected]) {
//        CommonDownloadWebServices *ws = [[CommonDownloadWebServices alloc] init];
//        [ws setDelegate:self];
//        [ws getWebServicesData:[localBookItem bookId] type:@"f"];
//        [ws release];
//    }
}

-(void)cancleDownload:(id)sender {
    
}


#pragma mark -
#pragma mark SotoreKit method
- (void) requestProductData {
	if ([SKPaymentQueue canMakePayments]) {	
        SKProductsRequest *request= [[SKProductsRequest alloc] initWithProductIdentifiers:[NSSet setWithObject:[[localBookItem bookCode] stringByReplacingOccurrencesOfString:@".a01." withString:@".a02."]]];
//        NSLog(@"product id:%@", [[localBookItem bookCode] stringByReplacingOccurrencesOfString:@".a01." withString:@".a02."]);
		//SKProductsRequest *request= [[SKProductsRequest alloc] initWithProductIdentifiers:[NSSet setWithObject:@"com.cjcb.a01.b1000"]];
        //NSLog(@"bookCode:%@", [localBookItem bookCode]);
		request.delegate = self;
		[request start];
	}else{		
		UIAlertView *alerView =  [[UIAlertView alloc] initWithTitle:@"警告" 
                                                            message:@"苹果应用商店（App Store）不可用。"
														   delegate:nil 
                                                  cancelButtonTitle:@"确定" otherButtonTitles:nil];
		
		[alerView show];
		[alerView release];
		//[m_buyButton setEnabled:YES];
	}
}

#pragma mark request delegate
//收到产品的消息
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response {
	NSArray *myProduct = response.products;
	//NSLog(@"the count of products is %d", [myProduct count]);
    /*
     NSArray *products = response.products;
     SKProduct *proUpgradeProduct = [products count] == 1 ? [[products firstObject] retain] : nil;
     if (proUpgradeProduct)
     {
     NSLog(@"Product title: %@" , proUpgradeProduct.localizedTitle);
     NSLog(@"Product description: %@" , proUpgradeProduct.localizedDescription);
     NSLog(@"Product price: %@" , proUpgradeProduct.price);
     NSLog(@"Product id: %@" , proUpgradeProduct.productIdentifier);
     }
     
     for (NSString *invalidProductId in response.invalidProductIdentifiers)
     {
     NSLog(@"Invalid product id: %@" , invalidProductId);
     }
     */
    // finally release the reqest we alloc/init’ed in requestProUpgradeProductData
    //[productsRequest release];
	
	BOOL bIsExist = NO;
	for(SKProduct *product in myProduct){
		SKPayment *payment = [SKPayment paymentWithProductIdentifier:[product productIdentifier]];
        //NSLog(@"product productIdentifier:%@", [product productIdentifier]);
		[[SKPaymentQueue defaultQueue] addPayment:payment];
		[request release];
	    //启动时间检测
		bIsExist = YES;
	}
	
	if (!bIsExist) {
		UIAlertView *alertView =  [[UIAlertView alloc] initWithTitle:@"提示" 
                                                             message:@"该商品在等待苹果应用商店（App Store)审核，审核后即可购买。"
                                                            delegate:nil 
                                                   cancelButtonTitle:@"关闭"
                                                   otherButtonTitles:nil];
		[alertView show];
		[alertView release];
        
		//[m_buyButton setEnabled:YES];
	}
}


- (void)request:(SKRequest *)request didFailWithError:(NSError *)error {
	UIAlertView *alertView =  [[UIAlertView alloc] initWithTitle:@"错误" message:[error localizedDescription]
                                                        delegate:nil cancelButtonTitle:@"关闭" otherButtonTitles:nil];
	
	[alertView show];
	[alertView release];
}


- (void)dismissReaderViewController:(ReaderViewController *)viewController {
	HubuAppDelegate *delegate = [[UIApplication sharedApplication] delegate];
	[delegate.hubuViewController dismissModalViewControllerAnimated:YES];
}


//Web服务调用的返回值
- (void)onCommonDownloadWebServicesOver:(NSString *)success {
    //NSLog(@"success:%@", success);
}

- (void)onCommonDownloadWebServicesFaild:(NSString *)error {
    NSLog(@"error:%@", error);
}
@end
